﻿using System;
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MaxStoreShop.Core.Ui
{
    public class ExtendedDataGrid : DataGrid
    {
        public Action<object, DataGridRowEditEndingEventArgs> OnRowChanged;
        public Action<object, object, RowDeletingEventArgs> OnRowDeleting;

        public ExtendedDataGrid()
        {
            SetCurrentValue(CanUserDeleteRowsProperty, false);
            SetCurrentValue(AutoGenerateColumnsProperty, false);
            SetCurrentValue(CanUserAddRowsProperty, true);
            SetCurrentValue(CanUserSortColumnsProperty, true);
            ApplyDataGridStyle();
            RowEditEnding += MainDataGridOnRowEditEnding;
            PreviewKeyDown += PreviewKeyDownHandler;
        }

        void ApplyDataGridStyle()
        {
            var defaultStyle = (Style)FindResource(typeof(DataGrid));
            Style = defaultStyle;
        }

        void MainDataGridOnRowEditEnding(object sender, DataGridRowEditEndingEventArgs dataGridRowEditEndingEventArgs)
        {
            if (dataGridRowEditEndingEventArgs.EditAction == DataGridEditAction.Cancel)
                return;

            if (RowValidationRules.Any(rowValidationRule => !rowValidationRule.Validate(dataGridRowEditEndingEventArgs.Row.BindingGroup,
                CultureInfo.InvariantCulture).IsValid))
            {
                return;
            }

            if (OnRowChanged != null)
                OnRowChanged(sender, dataGridRowEditEndingEventArgs);

//            if (dataGridRowEditEndingEventArgs.Cancel)
//            {
//                var dataGrid = sender as DataGrid;
//                if (dataGrid != null)
//                    dataGrid.CancelEdit();
//            }
        }

        void PreviewKeyDownHandler(object sender, KeyEventArgs e)
        {
            var grid = (DataGrid)sender;
            if (e.Key != Key.Delete)
                return;

            if (ItemsSource == null)
                return;

            if (grid.SelectedItems == null || grid.SelectedItems.Count == 0)
                return;


            var itemsList = grid.SelectedItems.Cast<object>().ToList();
            foreach (var row in itemsList)
            {
                if (OnRowDeleting != null)
                {
                    var args = new RowDeletingEventArgs();
                    OnRowDeleting(this, row, args);
                    if (args.Cancel)
                        continue;
                }

                var items = ItemsSource as IList;
                if (items == null)
                    continue;

                items.Remove(row);
            }
        }
    }
}
